﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using Jumpton.SFA.Server.BusinessRule;
using Jumpton.SFA.Server.BusinessRule.GIS;
using Jumpton.SFA.Server.BusinessRule.System;
using Jumpton.Persistent;
using Jumpton.SFA.Server.Entity;
using Jumpton.SFA.Server.BusinessRule.CallRoute;
using System.Net;
using Jumpton.SFA.Server.BusinessRule.MasterData;
using Jumpton.SFA.Server.BusinessRule.Traffic;
public partial class Order_Delivery : PageBase, ICallbackEventHandler
{
    GISManager gisManager = new GISManager();
    StateManager stateManager = new StateManager();
    OrgainzationManager orgManager = new OrgainzationManager();
    static DataSet ds = null;
    public string _content;
    public static string customerids = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
           
          
            if (txtHidOrg.Value == "")
            {
                InitForm();
                DataBind();
            }

            BindUser();
            getCustomers();
            BindTruck();
            BindWarehouse();
        } 
    }

    private void BindUser()
    {
        ddl_chains.Items.Clear();

        if (!string.IsNullOrEmpty(txtHidUsers.Value))
        {
            string[] options = txtHidUsers.Value.Split('∮');

            for (int i = 0; i < options.Length; i++)
            {
                string[] item = options[i].Split('∞');
                ddl_chains.Items.Add(new ListItem(item[1], item[0]));
            }
        }
        ddl_chains.Items.Insert(0, new ListItem("--请选择--", ""));
    }


    private void BindWarehouse()
    {
       ddl_Warehouse.DataSource=WareHouseManager.GetWareHouse(MyStateManager.DomainID);
       ddl_Warehouse.DataTextField = "DESCRIPTION";
       ddl_Warehouse.DataValueField = "WareHouseCode";
       ddl_Warehouse.DataBind();
       ddl_Warehouse.Items.Insert(0,new ListItem("--请选择--",""));
    }

    private void BindTruck()
    {
        TrafficManager tm = new TrafficManager();
        ObjectTable ot = tm.GetTrucks(MyStateManager.DomainID, "", "1", "");
        ddl_truck.DataTextField = "CODE";
        ddl_truck.DataValueField = "ID";
        ddl_truck.DataSource = ot;
        ddl_truck.DataBind();
        ddl_truck.Items.Insert(0, new ListItem("--请选择--", ""));
    }

    private void InitForm()
    {
        txtHidOrg.Value = OrgHidValue;
        txtOrg.Text = OrgShowValue;
        var data = new OrgainzationManager().SearchOrgTree(MyStateManager.DomainID, MyStateManager.OrgID, null);
        if (data.Rows.Count != 1 || new Jumpton.SFA.Server.BusinessRule.System.UserManager().isManager(MyStateManager.PersonID))
        {
            OrgHelper.BindUsersDDL(MyStateManager.DomainID, this.txtHidOrg.Value, this.ddl_chains);
        }
        else
        {
            Person person = new PersonManager().Load(MyStateManager.PersonID);
            ddl_chains.Items.Clear();
            ddl_chains.Items.Add(new ListItem(person.Name, MyStateManager.UserID.ToString()));
        }
        //OrgHelper.BindUsersDDL(this.MyStateManager.DomainID, txtHidOrg.Value, ddlUserList);

      
    }


    public void RaiseCallbackEvent(string the_string)
    {
        _content = the_string;
    }

    public string GetCallbackResult()
    {
        //  拆分由客户端传过来的参数
        string[] parts = _content.Split('|');

        //  生成ServerMethod的参数队列
        object[] theArgs = new object[parts.Length - 1];
        for (int int_index = 1; int_index < parts.Length; int_index++)
            theArgs[int_index - 1] = parts[int_index];

        //  调用ServerMethod
        return (string)GetType().GetMethod(parts[0]).Invoke(this, theArgs);
    }

    public string UpdateVisits(string args)
    {
        string[] theArgs = args.Split('#');

        DataTable dtLocation = gisManager.GetVisitLocation(theArgs[0], DateTime.Parse(theArgs[1]));
        string jsUsers = "";
        if (dtLocation.Rows.Count > 0)
        {
            jsUsers = AjaxFactory.DataTableJson(dtLocation);

        }
        return jsUsers;
    }

   

    protected void txtOrg_TextChanged(object sender, EventArgs e)
    {
        BindUser();
    }



    protected void btn_serch_Click(object sender, EventArgs e)
    {
        string orderids = hid_orderids.Value;
        if (orderids != "")
        {
            ds = OrderHeaderManager.GetOrderHeadersList(" and oh.CUSTOMER_ID IN(" + orderids + ") and oh.status=0 ");
            gvOrders.DataSource = ds.Tables[0];
            gvOrders.DataBind();    
        }
        else
        {
            gvOrders.DataSource = null;
            gvOrders.DataBind();
           
        }
       
    }
    protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
    {

    }

    public void getCustomers()
    {
        string customers = "";
        DataSet dataset = CustomerManager.SearchCustomer(" AND C.DOMAIN_ID="+MyStateManager.DomainID);
        DataTable dt = dataset.Tables[0];
        if (!IsPostBack)
        {
            ddl_customers.DataSource = dt;
            ddl_customers.DataTextField = "NAME";
            ddl_customers.DataValueField = "ID";

            ddl_customers.DataBind();
            ddl_customers.Items.Insert(0, new ListItem("--全部--", ""));
        }
       


        foreach (DataRow dr in dt.Rows)
        {
            customers += dr["ID"] + ","+dr["NAME"]+","+ dr["IDENTITY1"] + "," + dr["IDENTITY2"] + "|";
        }
        if(customers!="")
            customerids = customers.Substring(0, customers.Length - 1);

        if (dt.Rows.Count <= 0)
            customerids = "";
       
    }
    protected void btn_del_Click(object sender, EventArgs e)
    {
        if (ds == null)
        {
            ds = OrderHeaderManager.GetOrderHeadersList(" and oh.CUSTOMER_ID IN(" + hid_orderids.Value + ") ");
        }
        for (int i = 0; i < gvOrders.Rows.Count; i++)
        {
            GridViewRow gr=gvOrders.Rows[i];
             CheckBox chk = gr.FindControl("cbxSelected") as CheckBox;
            if (chk != null&&chk.Checked)
            {
                string cid = ds.Tables[0].Rows[i]["CUSTOMER_ID"].ToString();
                hid_orderids.Value = hid_orderids.Value.Replace(cid, "");
                if (hid_orderids.Value.StartsWith(","))
                    hid_orderids.Value = hid_orderids.Value.Substring(1);
                if (hid_orderids.Value.EndsWith(","))
                    hid_orderids.Value = hid_orderids.Value.Substring(0, hid_orderids.Value.Length - 1);
                
                   ds.Tables[0].Rows[i].Delete();
                
            }
        }
        ScriptManager.RegisterStartupScript(this, GetType(), "", "setValue('"+hid_orderids.Value+"')", true);
        ds.Tables[0].AcceptChanges();
        gvOrders.DataSource = ds.Tables[0];
        gvOrders.DataBind();
    }
    protected void gvOrders_DataBound(object sender, EventArgs e)
    {
        if (gvOrders.Rows.Count > 0)
        {
            btn_submit.Visible = true;
            btn_del.Visible = true;
        }
        else
        {
            btn_submit.Visible = false;
            btn_del.Visible = false;
        }
    }
    protected void btn_submit_Click(object sender, EventArgs e)
    {

        if (ValidateDatetime()&&RequiredFieldValidator3.IsValid && RequiredFieldValidator1.IsValid)
        {
            DELIVERY_ROUTE droute = new DELIVERY_ROUTE();
            ORDER_HEADERS oh = null;

            TrafficManager tfm = new TrafficManager();
            OrderHeaderManager ohm = new OrderHeaderManager();
            int row = 0;
            bool successful = true;
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                CheckBox chkselect = gvOrders.Rows[row].FindControl("cbxSelected") as CheckBox;
                if (chkselect != null && chkselect.Checked)
                {
                    TextBox txtPlanST = gvOrders.Rows[row].FindControl("txtPlanST") as TextBox;
                    TextBox txtPlanET = gvOrders.Rows[row].FindControl("txtPlanET") as TextBox;
                    if (txtPlanST != null && txtPlanET != null)
                    {
                        if (txtPlanST.Text.Equals(string.Empty))
                        {
                            ShowMessage("请选择计划开始时间");
                            return;
                        }
                        else if (txtPlanET.Text.Equals(string.Empty))
                        {
                            ShowMessage("请选择计划结束时间");
                            return;
                        }
                        else
                        {
                            droute.PLAN_ST = BusinessLogic.GetStringDateTimeDecimal(txtPlanST.Text.Trim());
                            droute.PLAN_ET = BusinessLogic.GetStringDateTimeDecimal(txtPlanET.Text.Trim());
                        }
                    }
                    droute.SHIP_FROM_CODE = ddl_Warehouse.SelectedValue;
                    droute.TRUCKS_CODE = ddl_truck.SelectedItem.Text;
                    droute.USERID = MyStateManager.UserID;
                    droute.CUSTOMERID = decimal.Parse(dr["CUSTOMER_ID"].ToString());
                    droute.ORDER_ID = decimal.Parse(dr["ORDER_NO"].ToString());
                    droute.ACTIVE = true;
                    droute.DOMAINID = MyStateManager.DomainID;

                    droute.LAST_UPDATE_TIME = BusinessLogic.GetDateTimeDecimal(DateTime.Now);
                    droute.LAST_UPDATER = MyStateManager.UserID.ToString();
                    oh = ohm.Load(droute.ORDER_ID);
                    if (oh == null)
                    {
                        ShowMessage("提交失败未找到订单：" + droute.ORDER_ID);
                        return;
                    }
                    if (tfm.Save(droute))
                    {
                        try
                        {
                            oh.STATUS = 4;//已发货
                            ohm.Save(oh);

                        }
                        catch (Exception ex)
                        {

                            Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(
                     Jumpton.SFA.Server.BusinessRule.System.LogType.GENERAL_EXCEPTION, this.MyStateManager.Name,
                     this.MyStateManager.UserID, "分配订单更新状态 - 异常:订单号：" + droute.ORDER_ID + " 异常信息：" + ex.Message);
                            successful = false;
                        }
                    }
                }
                row++;

            }

            if(successful)
                ShowMessage("操作成功",Request.Url.ToString());
            else
                ShowMessage("操作失败");
        }
    }

    protected void btnSrh_Click(object sender, EventArgs e)
    {
        if (ddl_customers.SelectedValue != "")
        {
            getCustomers();
            customerids = customerids.Substring(customerids.IndexOf(ddl_customers.SelectedValue));
            if (customerids.Contains("|"))
                customerids = customerids.Substring(0, customerids.Length - (customerids.Substring(customerids.IndexOf("|")).Length));
            hid_orderids.Value = "";

            btn_serch_Click(sender, e);
        }
        else
        {
            getCustomers();
           
        }
    }

    public bool ValidateDatetime()
    {
        bool flg=true;
        foreach (GridViewRow gvr in gvOrders.Rows)
        {
            RequiredFieldValidator rf1 = gvr.FindControl("RequiredFieldValidator55") as RequiredFieldValidator;
            RequiredFieldValidator rf2 = gvr.FindControl("RequiredFieldValidator66") as RequiredFieldValidator;
            CheckBox chkselect = gvr.FindControl("cbxSelected") as CheckBox;
            if (chkselect != null && chkselect.Checked)
            {

                if (rf1 != null)
                    if (!rf1.IsValid)
                    {
                        flg = false;
                        //break;
                    }
                if (rf2 != null)
                    if (!rf2.IsValid)
                    {
                        flg = false;
                        //break;
                    }
            }
            else
            {
                rf1.IsValid = true;
                rf2.IsValid = true;
            }
        }
        return flg;
    }



   
}
